package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.approve;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.wxInform.WxInformBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.impl.TApprovalTemplateServiceImpl;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.Constructor.TApproveInfoDetail2GetApproveInfoDetailVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.Constructor.TUserApproveConn2GetUserApproveVo;
import com.xiaoxu.intranetweb.util.StringUtils;
import com.xiaoxu.intranetweb.util.SzResult;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Component
public class ApproveBu {
    @Autowired
    private ITApproveService approveService;
    @Autowired
    private ITUserApproveConnService userApproveConnService;
    @Autowired
    private TApprovalTemplateServiceImpl approvalTemplateService;
    @Autowired
    private TUserApproveConn2GetUserApproveVo tUserApproveConn2GetUserApproveVo;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private ITApproveInfoService approveInfoService;
    @Autowired
    private ITApproveInfoDetailService approveInfoDetailService;
    @Autowired
    private TApproveInfoDetail2GetApproveInfoDetailVo tApproveInfoDetail2GetApproveInfoDetailVo;
    @Autowired
    private ISysFilesService fileBu;
    @Autowired
    private WxInformBu wxInformBu;

    //   获取所有的审批类型
    public SzResult getApprove(String approveExplain, String plantId) throws Exception {
        QueryWrapper<TApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DEL_FLAG", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        queryWrapper.like(approveExplain != null && !approveExplain.isEmpty(), "APPROVE_EXPLAIN", approveExplain);
//        返回list
        List<Object> list = approveService.list(queryWrapper).stream().map(item -> {
            ApproveVo approveVo = new ApproveVo();
            BeanUtils.copyProperties(item, approveVo);
            TApprovalTemplate approvalTemplate = approvalTemplateService.getById(item.getTemplateId());
            if (approvalTemplate != null) {
                approveVo.setTemplateName(approvalTemplate.getTemplateName());
                approveVo.setApproveTemplate(approvalTemplate.getApproveTemplate());
            }
            return approveVo;
        }).collect(Collectors.toList());
        return SzResult.success(list);
    }

    //   获取所有的审批类型,不带未启用的
    public SzResult getApproveIsOn(String approveExplain, String plantId) throws Exception {
        QueryWrapper<TApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DEL_FLAG", 0);
        queryWrapper.eq("DATA_FROM", plantId);
        queryWrapper.eq("IF_ON", 1);
        queryWrapper.like(approveExplain != null && !approveExplain.isEmpty(), "APPROVE_EXPLAIN", approveExplain);
//        返回list
        List<Object> list = approveService.list(queryWrapper).stream().map(item -> {
            ApproveVo approveVo = new ApproveVo();
            BeanUtils.copyProperties(item, approveVo);
            TApprovalTemplate approvalTemplate = approvalTemplateService.getById(item.getTemplateId());
            if (approvalTemplate != null) {
                approveVo.setTemplateName(approvalTemplate.getTemplateName());
                approveVo.setApproveTemplate(approvalTemplate.getApproveTemplate());
            }
            return approveVo;
        }).collect(Collectors.toList());
        return SzResult.success(list);
    }

    //新增个人级别审批权限
    public SzResult addApprove(String approveName, String approveExplain, Integer approveTier, String templateId, String token, String plantId) throws Exception {
        StringBuilder logMsg = new StringBuilder();
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        QueryWrapper<TApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATA_FROM", plantId);
        queryWrapper.eq("DEL_FLAG", 0);
//        return SzResult.Error("请等待升级...");
        List<TApprove> tApproveList = approveService.list(queryWrapper);
        for (TApprove tApprove : tApproveList) {
            if (tApprove.getApproveExplain().equals(approveExplain)) {
                return SzResult.error("审批类型已存在");
            }
            if (tApprove.getApproveName().equals(approveName)) {
                return SzResult.error("审批名称已存在");
            }
        }
        TApprove tApprove = new TApprove();
        tApprove.setApproveName(approveName);
        tApprove.setApproveExplain(approveExplain);
        tApprove.setApproveTier(approveTier);
        tApprove.setTemplateId(templateId);
        tApprove.setDelFlag(0);
        tApprove.setDataFrom(plantId);
        tApprove.setIfOn(1);
        tApprove.setIfSystem(2);

        approveService.save(tApprove);
        logMsg.append("审批类型").append(approveExplain).append("新增成功;");
        sysLogBu.logRecord("授权审批权限", sysUser.getTrueName(), logMsg.toString(), plantId);
        return SzResult.success("新增成功");
    }

    //删除审批类型
    public SzResult deleteApprove(String id, String token, String plantId) throws Exception {
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        StringBuilder logMsg = new StringBuilder();
        QueryWrapper<TApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        queryWrapper.eq("DATA_FROM", plantId);
        TApprove tApprove = approveService.getOne(queryWrapper);
        if (tApprove == null) {
            return SzResult.error("审批类型不存在");
        }
        tApprove.setDelFlag(1);
        approveService.updateById(tApprove);
        logMsg.append("审批类型").append(tApprove.getApproveExplain()).append("删除成功;");
        sysLogBu.logRecord("删除审批类型", sysUser.getTrueName(), logMsg.toString(), plantId);
        return SzResult.success("删除成功");
    }

    //    编辑审批权限
    public SzResult updateApprove(String id, Integer approveTier, Integer ifOn, String templateId, String token, String plantId) throws Exception {
        StringBuilder logMsg = new StringBuilder();
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        // String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        QueryWrapper<TApprove> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("ID", id);
        TApprove tApprove = approveService.getOne(queryWrapper3);
        tApprove.setTemplateId(templateId);
        if (tApprove == null) {
            return SzResult.Error("审批类型不存在");
        }
//      如果层级变低，要先把高级的人权限卸掉
//        approveTier不为空
        if (approveTier != null) {
            if (approveTier < tApprove.getApproveTier()) {
                QueryWrapper<TUserApproveConn> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("APPROVE_ID", id);
//            queryWrapper.eq("APPROVE_TIER",tApprove.getApproveTier());应该是小于等于tApprove.getApproveTier()大于等于approveTier，但是这样写会报错
                queryWrapper.between("APPROVE_TIER", approveTier, tApprove.getApproveTier());
//      拿到有多少条
                long count = userApproveConnService.count(queryWrapper);
                if (count > 0) {
                    SzResult.Error("请先卸掉高级别的人的权限，再降低层级");
                }
            }
            if (!approveTier.equals(tApprove.getApproveTier())) {
                tApprove.setApproveTier(approveTier);
                logMsg.append("层级由").append(tApprove.getApproveTier()).append("修改为").append(approveTier).append(";");
            }
        }
//判断是否修改了层级
//        ifOn不为空
        if (ifOn != null) {
            if (!ifOn.equals(tApprove.getIfOn())) {
                tApprove.setIfOn(ifOn);
                logMsg.append("是否启用由").append(tApprove.getIfOn()).append("修改为").append(ifOn).append(";");
            }
        }
        if (logMsg.length() != 0) {
            approveService.updateById(tApprove);
            sysLogBu.logRecord("授权审批权限", sysUser.getTrueName(), "修改【" + tApprove.getApproveExplain() + "】审批权限，" + logMsg, plantId);
        }
        return SzResult.Success();
    }

    //获取所有审批信息
    public SzResult getApproveInfo(Integer page, Integer pageSize, String startTime, String endTime, String approveId, Integer approveState,String approveInfo, String token, String plantId) throws Exception {
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<TUserApproveConn> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("USER_ID", sysUser.getId());
        List<TUserApproveConn> list = userApproveConnService.list(queryWrapper1);
        List<String> approveIds = new ArrayList<>();
        for (TUserApproveConn tUserApproveConn : list) {
            approveIds.add(tUserApproveConn.getApproveId());
        }
        Page<TApproveInfo> page1 = new Page<>(page, pageSize);
        QueryWrapper<TApproveInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(approveInfo !=null && !approveInfo.equals(""), "APPROVE_INFO",approveInfo);
        queryWrapper.in(!approveIds.isEmpty(), "APPROVE_ID", approveIds);
//        between
        queryWrapper.between(startTime != null && !startTime.equals("") && endTime != null && !endTime.equals(""),
                "CREATE_TIME", startTime, endTime);
        queryWrapper.eq(approveId != null && !approveId.equals(""), "APPROVE_ID", approveId);
        queryWrapper.eq(approveState != null, "APPROVE_STATE", approveState);
        queryWrapper.eq("DATA_FROM", plantId);
        queryWrapper.eq("DEL_FLAG",0);
        queryWrapper.orderByDesc("CREATE_TIME");
        approveInfoService.page(page1, queryWrapper);

        List<TApproveInfo> records = page1.getRecords();
        List<GetApproveInfoVo> getApproveInfoVos = new ArrayList<>();
        for (TApproveInfo record : records) {
            QueryWrapper<TApprove> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("ID", record.getApproveId());
            TApprove tApprove = approveService.getOne(queryWrapper2);
            GetApproveInfoVo getApproveInfoVo = new GetApproveInfoVo();
            JSONObject executionData = JSONObject.parseObject(record.getExecutionData());
            if (executionData != null) {
                if (executionData.getString("serialNumber") !=null) {
                    getApproveInfoVo.setSerialNumber(executionData.getString("serialNumber"));
                }else {
                    getApproveInfoVo.setSerialNumber("");
                }
            }else {
                getApproveInfoVo.setSerialNumber("");
            }
            getApproveInfoVo.setApproveState(record.getApproveState());
            getApproveInfoVo.setApproveTier(tApprove.getApproveTier());
            getApproveInfoVo.setApproveName(tApprove.getApproveExplain());
            getApproveInfoVo.setApproveId(record.getApproveId());
            getApproveInfoVo.setCreateTime(record.getCreateTime());
            getApproveInfoVo.setApproveInfo(record.getApproveInfo());
            getApproveInfoVo.setApproveRemark(record.getApproveRemark());
            getApproveInfoVo.setCreateBy(record.getCreateBy());
            getApproveInfoVo.setDataFrom(record.getDataFrom());
            getApproveInfoVo.setTemplateId(tApprove.getTemplateId());
            TApprovalTemplate approvalTemplate = approvalTemplateService.getById(tApprove.getTemplateId());
            getApproveInfoVo.setApproveTemplate(approvalTemplate.getApproveTemplate());
            QueryWrapper<SysFiles> sysFilesQueryWrapper = new QueryWrapper<>();
            sysFilesQueryWrapper.eq("CONN_ID", record.getId());
            getApproveInfoVo.setIsFile(fileBu.getOne(sysFilesQueryWrapper) == null ? 0 : 1);
            QueryWrapper<SysFiles> sysFilesQueryWrapper1 = new QueryWrapper<>();
            sysFilesQueryWrapper1.eq("CONN_ID", record.getId()+1);
            getApproveInfoVo.setIsAttachment(fileBu.getOne(sysFilesQueryWrapper1) == null ? 0 : 1);
            getApproveInfoVo.setId(record.getId());
            getApproveInfoVos.add(getApproveInfoVo);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", page1.getTotal());
        map.put("list", getApproveInfoVos);
        return SzResult.success(map);
    }

    public SzResult uploadInfoFile(MultipartFile file, String id, String token) throws Exception {
        QueryWrapper<SysFiles> sysFilesQueryWrapper = new QueryWrapper<>();
        sysFilesQueryWrapper.eq("CONN_ID", id);
        if (fileBu.getOne(sysFilesQueryWrapper) != null) {
            return SzResult.success("已有上传文件");
        }
//    fileName去掉type
        String fileName = file.getOriginalFilename();
//        绝对文件名
        String absoluteFileName = fileName.substring(0, fileName.lastIndexOf("."));
//        fileType
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFileName = uuid + suffix;
//        项目路径下的upload文件夹
        File upload = new File("upload");
        if (!upload.exists()) {
            upload.mkdirs();
        }
// 获取当前年份和月份
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        String currentMonth = LocalDateTime.now().format(formatter);
// 创建以月份为名的文件夹
        File monthFolder = new File(upload.getAbsolutePath() + File.separator + currentMonth);

        if (!monthFolder.exists()) {
            monthFolder.mkdirs();
        }
// 设置文件存放的路径
        String filePath = monthFolder.getAbsolutePath() + File.separator;

        File dest = new File(filePath + newFileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);
        SysFiles sysFiles = new SysFiles();
        sysFiles.setId(uuid);
        sysFiles.setConnId(id);
        sysFiles.setUploadFrom(StpUtil.getLoginIdByToken(token).toString());
        sysFiles.setFileName(fileName);
        sysFiles.setFilePath(filePath);
        sysFiles.setFileSize(String.valueOf(file.getSize()));
        sysFiles.setFileType(suffix.replace(".", ""));
        sysFiles.setUploadTime(LocalDateTime.now());
        fileBu.save(sysFiles);
        return SzResult.success(sysFiles);
    }

    public void downloadInfoFile(String id, HttpServletResponse response) {
        try {
            QueryWrapper<SysFiles> sysFilesQueryWrapper = new QueryWrapper<>();
            sysFilesQueryWrapper.eq("CONN_ID", id);
            SysFiles sysFiles = fileBu.getOne(sysFilesQueryWrapper);
            Path path = Paths.get(sysFiles.getFilePath() + sysFiles.getId() + "." + sysFiles.getFileType());
            String fileName = sysFiles.getFileName();
            InputStream inputStream = new BufferedInputStream(Files.newInputStream(new File(path.toString()).toPath()));
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setHeader("Content-Length", "" + path.toFile().length());
            response.setHeader("Content-Disposition", "attachment; filename*=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            response.setStatus(500);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            e.printStackTrace();
        }
    }

    public SzResult deleteInfoFile(String id) {
        QueryWrapper<SysFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CONN_ID", id);
        SysFiles sysFiles = fileBu.getOne(queryWrapper);
        String filePath = sysFiles.getFilePath();
        String fileType = sysFiles.getFileType();
        File file = new File(filePath + sysFiles.getId() + "." + fileType);
        if (file.exists()) {
            file.delete();
        }
        return SzResult.success(fileBu.removeById(sysFiles.getId()));
    }

    //新增审批信息
    public SzResult addApproveInfo(String token, String plantId, String approveId, String approveInfo, JSONObject jsonObject) throws Exception {
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        // String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        TApproveInfo tApproveInfo = new TApproveInfo();
        tApproveInfo.setApproveId(approveId);
        tApproveInfo.setApproveState(0);
        TApprove approve = approveService.getById(approveId);
        tApproveInfo.setApproveTier(approve.getApproveTier());
        tApproveInfo.setCreateBy(sysUser.getTrueName());
        tApproveInfo.setExecutionData(jsonObject.toString());
        tApproveInfo.setApproveInfo(approveInfo);
        tApproveInfo.setCreateTime(LocalDateTime.now());
        tApproveInfo.setDataFrom(plantId);
        QueryWrapper<TUserApproveConn> userApproveConnQueryWrapper = new QueryWrapper<>();
        userApproveConnQueryWrapper.eq("APPROVE_ID",approveId);
        userApproveConnQueryWrapper.eq("APPROVE_TIER","1");
        for (TUserApproveConn tUserApproveConn : userApproveConnService.list(userApproveConnQueryWrapper)) {
            wxInformBu.processesApprovalInformFeign(tUserApproveConn.getUserId(),tApproveInfo.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),sysUser.getTrueName());
        }

        return SzResult.success(approveInfoService.save(tApproveInfo));
    }

    //    修改审批信息里的备注
    public SzResult updateApproveInfo(String token, String id, String remark, String plantId) throws Exception {
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        QueryWrapper<TApproveInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TApproveInfo tApproveInfo = approveInfoService.getOne(queryWrapper);
        if (tApproveInfo == null) {
            return SzResult.Error("审批信息不存在");
        }
//        if (!tApproveInfo.getApproveState().equals(0)) {
//            return SzResult.error("审批信息已审批，不可修改");
//        }
        tApproveInfo.setApproveRemark(remark);
        approveInfoService.updateById(tApproveInfo);
        return SzResult.Success();
    }

    //    获取审批信息详情
    public SzResult getApproveInfoDetail(String approveInfoId, String plantId) throws Exception {
        QueryWrapper<TApproveInfoDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("APPROVE_INFO_ID", approveInfoId);
        queryWrapper.orderByAsc("APPROVE_TIER");
        List<TApproveInfoDetail> list = approveInfoDetailService.list(queryWrapper);
        List<GetApproveInfoDetailVo> list1 = new LinkedList<>();
        for (TApproveInfoDetail tApproveInfoDetail : list) {
            GetApproveInfoDetailVo getApproveInfoDetailVo = new GetApproveInfoDetailVo();
            BeanUtils.copyProperties(tApproveInfoDetail,getApproveInfoDetailVo);
            SysUser sysUser = userInfoDao.getUser(tApproveInfoDetail.getApproveUserId());
            getApproveInfoDetailVo.setApproveUserName(sysUser.getTrueName());
            String approveId = approveInfoService.getById(approveInfoId).getApproveId();
            QueryWrapper<TUserApproveConn> userApproveConnQueryWrapper = new QueryWrapper<>();
            userApproveConnQueryWrapper.eq("USER_ID",tApproveInfoDetail.getApproveUserId());
            userApproveConnQueryWrapper.eq("APPROVE_ID",approveId);
            userApproveConnQueryWrapper.eq("DATA_FROM", plantId);
            userApproveConnQueryWrapper.eq("APPROVE_TIER", tApproveInfoDetail.getApproveTier());
            TUserApproveConn userApproveConn = userApproveConnService.getOne(userApproveConnQueryWrapper);
            getApproveInfoDetailVo.setBranch(userApproveConn.getBranch());
            list1.add(getApproveInfoDetailVo);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", list.size());
        map.put("list", list1);
        return SzResult.success(map);
    }

    //删除授权
    public SzResult deleteUserApprove(String token, String id, String plantId) throws Exception {
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        QueryWrapper<TUserApproveConn> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TUserApproveConn tUserApproveConn = userApproveConnService.getOne(queryWrapper);
        if (tUserApproveConn == null) {
            return SzResult.Error("授权不存在");
        }
        userApproveConnService.remove(queryWrapper);
        SysUser sysUser1 = userInfoDao.getUser(tUserApproveConn.getUserId());
        QueryWrapper<TApprove> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ID", tUserApproveConn.getApproveId());
        TApprove tApprove = approveService.getOne(queryWrapper2);
        sysLogBu.logRecord("审批授权", sysUser.getTrueName(), "删除用户【" + sysUser1.getTrueName() + "】" + "的【" + tApprove.getApproveExplain() + "】" + "的" + tUserApproveConn.getApproveTier() + "级审批权限", plantId);
        return SzResult.Success();
    }

    //    获取授权根据授权方法的id，在TUserApproveConn表中查询所有的授权
    public SzResult getUserApprove(String id, String token, String plantId) throws Exception {
        // String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        QueryWrapper<TUserApproveConn> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("APPROVE_ID", id);
        queryWrapper.eq("DATA_FROM", plantId);
        queryWrapper.orderByDesc("APPROVE_TIER");
        List<TUserApproveConn> list = userApproveConnService.list(queryWrapper);
        List<GetUserApproveVo> list1 = new LinkedList<>();
        for (TUserApproveConn tUserApproveConn : list) {
            GetUserApproveVo getUserApproveVo = tUserApproveConn2GetUserApproveVo.getUserApproveVo(tUserApproveConn);
            list1.add(getUserApproveVo);
        }
        return SzResult.success(list1);
    }

    //    授权审批权限
    public SzResult addUserApprove(String token, String userId, String approveId, Integer approveTier, String branch, String plantId) throws Exception {

        QueryWrapper<TApprove> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ID", approveId);
        TApprove tApprove = approveService.getOne(queryWrapper2);
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<TUserApproveConn> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USER_ID", userId);
        queryWrapper.eq("APPROVE_ID", approveId);
        queryWrapper.eq("APPROVE_TIER", approveTier);
        if (userApproveConnService.count(queryWrapper) > 0) {
            return SzResult.error200("已经授权过了");
        }
//        授权的approveTier不能大于TApprove里的approveTier
        if (approveTier > tApprove.getApproveTier()) {
            return SzResult.error200("授权级别不能大于审批级别");
        }
//        不能为0或者负数
        if (approveTier <= 0) {
            return SzResult.error200("授权级别不能为0或者负数");
        }
        //新增审批授权前,先判断小于该级别的审批授权是否存在,不存在则不允许新增
        if (approveTier > 1) {
            QueryWrapper<TUserApproveConn> queryWrapper3 = new QueryWrapper<>();
//            queryWrapper3.eq("USER_ID", userId);
            queryWrapper3.eq("APPROVE_ID", approveId);
            queryWrapper3.eq("APPROVE_TIER", approveTier - 1);//小于
            queryWrapper3.eq("DATA_FROM", plantId);
            List<TUserApproveConn> list = userApproveConnService.list(queryWrapper3);
            if (list.size() == 0) {
                return SzResult.error200("请先授权小于该级别的审批权限");
            }
        }
        TUserApproveConn userApproveConn = new TUserApproveConn();
        userApproveConn.setUserId(userId);
        userApproveConn.setApproveId(approveId);
        userApproveConn.setApproveTier(approveTier);
        userApproveConn.setBranch(branch);
        userApproveConn.setCreateBy(sysUser.getId());
        userApproveConn.setCreateTime(String.valueOf(LocalDateTime.now()));
        userApproveConn.setDataFrom(plantId);
        userApproveConnService.save(userApproveConn);
        QueryWrapper<SysUser> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", userId);
        SysUser sysUser1 = userInfoDao.getUser(userId);
        sysLogBu.logRecord("审批授权", sysUser.getTrueName(), "给用户【" + sysUser1.getTrueName() + "】" + "授权【" + tApprove.getApproveExplain() + "】" + "的" + approveTier + "级审批权限", plantId);
        return SzResult.Success();
    }

    //    集成下面的两个审批方法到一个方法，通过state判断是通过还是驳回
    public SzResult approvalProcess(String token, String id, String remark, Integer state, String plantId) throws Exception {
        SzResult szResult = new SzResult();
        if (state == null) {
            return SzResult.error("请选择审批结果");
        }
        if (state == 1) {
            szResult = this.approvalProcessSuccess(token, id, remark, plantId);
        }
        if (state == 2) {
            szResult = this.approvalProcessFail(token, id, remark, plantId);
        }
        return szResult;
    }

    //    删除授权根据授权方法的id，在TUserApproveConn表中删除所有的授权
//    public SzResult deleteUserApproveByApproveId(String token,String id) throws Exception {
//        String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
//        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
//        QueryWrapper<TUserApproveConn> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("ID",id);
//        TUserApproveConn tUserApproveConn = userApproveConnService.getOne(queryWrapper);
//        userApproveConnService.remove(queryWrapper);
//        SysUser sysUser1 = userInfoDao.getUser(tUserApproveConn.getUserId());
//        QueryWrapper<TApprove> queryWrapper2 = new QueryWrapper<>();
//        queryWrapper2.eq("ID",tUserApproveConn.getApproveId());
//        TApprove tApprove = approveService.getOne(queryWrapper2);
//        sysLogBu.logRecord("审批授权",sysUser.getTrueName(),"删除用户【"+sysUser1.getTrueName()+"】"+"的【"+tApprove.getApproveExplain()+"】"+"的"+tUserApproveConn.getApproveTier()+"级审批权限",plantId);
//        return SzResult.Success();
//    }
//    审批通过方法
//  标准化审批流程-根据approveName先查询TApprove表，获取到对应的审批流程，然后根据审批流程的id查询TApproveProcess表，获取到对应的审批流程
//    state 1为通过，0驳回，null未审批
//    如果已经在中间驳回了，那么后面的审批人就不用审批了
    @Transactional
    public SzResult approvalProcessSuccess(String token, String id, String remark, String plantId) throws Exception {
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();

//      查洵审批信息
        QueryWrapper<TApproveInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ID", id);
        TApproveInfo tApproveInfo = approveInfoService.getOne(queryWrapper2);
        //        前端发来的审批信息名称，根据名称查询审批流程
        QueryWrapper<TApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", tApproveInfo.getApproveId());
        TApprove tApprove = approveService.getOne(queryWrapper);
//        根据审批流程的id查询审批人的审批等级
        QueryWrapper<TUserApproveConn> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("APPROVE_ID", tApprove.getId());
        queryWrapper1.eq("USER_ID", sysUser.getId());
        queryWrapper1.orderByAsc("APPROVE_TIER");
        List<TUserApproveConn> list = userApproveConnService.list(queryWrapper1);
        if (tApproveInfo.getApproveState() == 10) {
            return SzResult.error("审批已撤销");
        }
//            是否被驳回
        if (tApproveInfo.getApproveState() == 2) {
            return SzResult.error("当前审批已被驳回");
        }
        //    根据查出来的审批等级，查询审批详情，因为会存在一个人具有多级审批的权限，所以需要遍历
        for (int i = 0; i < list.size(); i++) {
            TUserApproveConn tUserApproveConn = list.get(i);
            //            如果这是他拥有的权限的最后一级审批，检查这一层有没有审批过，防止重复审批,可以判断i是不是最后一个了
            if (i == list.size() - 1) {
                QueryWrapper<TApproveInfoDetail> queryWrapper6 = new QueryWrapper<>();
                queryWrapper6.eq("APPROVE_INFO_ID", tApproveInfo.getId());
                queryWrapper6.eq("APPROVE_TIER", tUserApproveConn.getApproveTier());
                queryWrapper6.eq("DEL_FLAG", 0);
                TApproveInfoDetail tApproveInfoDetail4 = approveInfoDetailService.getOne(queryWrapper6);
                if (tApproveInfoDetail4 != null) {
                    return SzResult.error("已经审批过了");
                }
            }
//            检查这个等级是否有别人审批过了
            QueryWrapper<TApproveInfoDetail> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("APPROVE_INFO_ID", tApproveInfo.getId());
            queryWrapper3.eq("APPROVE_TIER", tUserApproveConn.getApproveTier());
            queryWrapper3.eq("DEL_FLAG", 0);
            TApproveInfoDetail tApproveInfoDetail = approveInfoDetailService.getOne(queryWrapper3);
//            是否有数据，有数据代表这一级审批已经结束，直接循环下一级，
            if (tApproveInfoDetail != null) {
                continue;
            }
//          比如说我有1级和三级权限，1级我审批了，2级别人还没审批，那么我就不能再审批了，要等别人审批完了，我才能审批
            QueryWrapper<TApproveInfoDetail> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.eq("APPROVE_INFO_ID", tApproveInfo.getId());
//            queryWrapper4.eq("APPROVE_TIER", tUserApproveConn.getApproveTier() - 1);//是不是可以用小于然后大于0来代替，除了1
            queryWrapper4.lt("APPROVE_TIER", tUserApproveConn.getApproveTier());//小于2
            queryWrapper4.gt("APPROVE_TIER", 0);//大于0
            queryWrapper4.eq("DEL_FLAG", 0);
            List<TApproveInfoDetail> tApproveInfoDetail2 = approveInfoDetailService.list(queryWrapper4);

            for (TApproveInfoDetail approveInfoDetail : tApproveInfoDetail2) {
                //            查1级的时候，tApproveInfoDetail2是null，所以要判断一下
                QueryWrapper<TApproveInfoDetail> queryWrapper5 = new QueryWrapper<>();
                queryWrapper5.eq("APPROVE_INFO_ID", tApproveInfo.getId());
                queryWrapper5.eq("APPROVE_TIER", 1);
                queryWrapper5.eq("DEL_FLAG", 0);
                TApproveInfoDetail tApproveInfoDetail3 = approveInfoDetailService.getOne(queryWrapper5);
                if (approveInfoDetail == null && tApproveInfoDetail3 != null) {
                    return SzResult.error("请等待上一级通过审批");
                }
            }
//            如果审批等级是最后一级，那么就直接通过审批
            TApproveInfoDetail tApproveInfoDetail1 = new TApproveInfoDetail();
            tApproveInfoDetail1.setApproveInfoId(tApproveInfo.getId());
            tApproveInfoDetail1.setApproveTier(tUserApproveConn.getApproveTier());
            tApproveInfoDetail1.setApproveUserId(tUserApproveConn.getUserId());
            tApproveInfoDetail1.setApproveState(1);
            tApproveInfoDetail1.setCreateTime(LocalDateTime.now());
            tApproveInfoDetail1.setApproveRemark(remark);
            tApproveInfoDetail1.setDelFlag(0);
            approveInfoDetailService.save(tApproveInfoDetail1);
//如果审批成功了就将tApproveInfo里的tier更新为当前审批的等级
            tApproveInfo.setApproveTier(tApproveInfoDetail1.getApproveTier());
            //如果当前审批等级不等于总等级进行下一等级推送
            if (!tApproveInfoDetail1.getApproveTier().equals(tApprove.getApproveTier())){
                String approveTier = String.valueOf(Integer.valueOf(tUserApproveConn.getApproveTier()) + 1);
                QueryWrapper<TUserApproveConn> userApproveConnQueryWrapper = new QueryWrapper<>();
                userApproveConnQueryWrapper.eq("APPROVE_ID",tApprove.getId());
                userApproveConnQueryWrapper.eq("APPROVE_TIER",approveTier);
                for (TUserApproveConn userApproveConn : userApproveConnService.list(userApproveConnQueryWrapper)) {
                    wxInformBu.processesApprovalInformFeign(userApproveConn.getUserId(),tApproveInfo.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),sysUser.getTrueName());
                }
            }
            if (Objects.equals(tApproveInfoDetail1.getApproveTier(), tApprove.getApproveTier())) {
                //                如果已经达到最后一层审批，就将审批信息的状态改为1
                tApproveInfo.setApproveState(1);
                approveInfoService.updateById(tApproveInfo);

//String financeEnterNum, String financeEnterCoId, String targetCoId, String token放到Object[]{}里面
//                以后不再执行反射完成审批，审批以后只是数据
//                Object[] object = new Object[]{tApproveInfo.getExecutionData(), sysUser};
//
//                this.approvalExecute(tApprove.getApproveName(), object);
            }
            break;
        }
        return SzResult.Success();
    }

    //    驳回审批：1.先判断TApproveInfo是否为0，
//    先查询用户被授权了那一层审批，然后根据审批流程的id查询审批信息，然后根据审批信息的id查询审批详情，然后根据审批详情的审批等级查询审批详情，然后修改审批详情的状态为0
//    要判断审批已经到哪一层，并且判断用户是否有这一层权限去驳回，如果没有权限，就返回错误信息，如果有权限，就修改审批详情的状态为0
//    驳回必须看当前审批已经到达那一层，然后根据审批等级去驳回，低等级的权限人员不能驳回高等级的审批，只能逐层驳回
    public SzResult approvalProcessFail(String token, String id, String remark, String plantId) throws Exception {
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        // String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
//        前端发来的审批信息名称，根据名称查询审批流程
//      查洵审批信息
        QueryWrapper<TApproveInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ID", id);
        TApproveInfo tApproveInfo = approveInfoService.getOne(queryWrapper2);
        //        前端发来的审批信息名称，根据名称查询审批流程
        QueryWrapper<TApprove> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", tApproveInfo.getApproveId());
        TApprove tApprove = approveService.getOne(queryWrapper);
        Integer approveState = tApproveInfo.getApproveState(); //审批状态
        if (approveState == 1) {
            return SzResult.Error("当前审批已通过");
        }
        if (approveState == 2) {
            return SzResult.Error("当前审批已被驳回");
        }
        //当前审批人的审批等级
        QueryWrapper<TUserApproveConn> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("APPROVE_ID", tApprove.getId());
        queryWrapper1.eq("USER_ID", sysUser.getId());
        queryWrapper1.orderByAsc("APPROVE_TIER");
        List<TUserApproveConn> tUserApproveConns = userApproveConnService.list(queryWrapper1);
        if (tUserApproveConns.size() == 0) {
            return SzResult.Error("当前用户没有审批权限");
        }
        for (int i = 0; i < tUserApproveConns.size(); i++) {
            TUserApproveConn tUserApproveConn = tUserApproveConns.get(i);
            //            如果直到所有审批都结束了
            if (i == tUserApproveConns.size() - 1) {
                QueryWrapper<TApproveInfoDetail> queryWrapper6 = new QueryWrapper<>();
                queryWrapper6.eq("APPROVE_INFO_ID", tApproveInfo.getId());
                queryWrapper6.eq("APPROVE_TIER", tUserApproveConn.getApproveTier());
                queryWrapper6.eq("DEL_FLAG", 0);
                TApproveInfoDetail tApproveInfoDetail4 = approveInfoDetailService.getOne(queryWrapper6);
                if (tApproveInfoDetail4 != null) {
                    return SzResult.error("已经审批过了");
                }
            }
//      如果当前审批已经审批过了
//            检查这个等级是否有别人审批过了
            QueryWrapper<TApproveInfoDetail> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("APPROVE_INFO_ID", tApproveInfo.getId());
            queryWrapper3.eq("APPROVE_TIER", tUserApproveConn.getApproveTier());
            queryWrapper3.eq("DEL_FLAG", 0);
            TApproveInfoDetail tApproveInfoDetail = approveInfoDetailService.getOne(queryWrapper3);
//            是否有数据，有数据代表这一级审批已经结束，直接循环下一级，
            if (tApproveInfoDetail != null) {
                continue;
            }

//            如果没有数据，代表这一级审批还没有结束，就修改这一级审批的状态为2
            TApproveInfoDetail tApproveInfoDetail1 = new TApproveInfoDetail();
            tApproveInfoDetail1.setApproveInfoId(tApproveInfo.getId());
            tApproveInfoDetail1.setApproveTier(tUserApproveConn.getApproveTier());
            tApproveInfoDetail1.setApproveUserId(tUserApproveConn.getUserId());
            tApproveInfoDetail1.setApproveState(2);
            tApproveInfoDetail1.setCreateTime(LocalDateTime.now());
            tApproveInfoDetail1.setApproveRemark(remark);
            tApproveInfoDetail1.setDelFlag(0);
            approveInfoDetailService.save(tApproveInfoDetail1);
//            然后更新审批信息为驳回
            tApproveInfo.setApproveState(2);
            approveInfoService.updateById(tApproveInfo);
            break;
        }
        return SzResult.Success();
    }

    //修改自己的审批意见
    public SzResult updateApprovalProcessDetail(String token, String remark, String id, Integer approveState) throws Exception {
//        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());

//        修改审批
        QueryWrapper<TApproveInfoDetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", id);
        queryWrapper1.eq("APPROVE_REMARK", remark);
        queryWrapper1.eq("APPROVE_STATE", approveState);
        TApproveInfoDetail tApproveInfoDetail = approveInfoDetailService.getOne(queryWrapper1);
//        根据tApproveInfoDetail查出tApproveInfo
        QueryWrapper<TApproveInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("ID", tApproveInfoDetail.getApproveInfoId());
        TApproveInfo tApproveInfo = approveInfoService.getOne(queryWrapper2);
//        Integer approveTier1 = tApproveInfo.getApproveTier();
//        根据tApproveInfo查出tApprove
//        QueryWrapper<TApprove> queryWrapper3 = new QueryWrapper<>();
//        queryWrapper3.eq("ID",tApproveInfo.getApproveId());
//        TApprove tApprove = approveService.getOne(queryWrapper3);
//        QueryWrapper<TUserApproveConn> queryWrapper = new QueryWrapper<>();
        //        拿到当前用户的最高审批等级，用max方法获取最大的APPROVE_TIER
//        queryWrapper.select("max(APPROVE_TIER) as APPROVE_TIER");
//        queryWrapper.eq("USER_ID",sysUser.getId());
//        queryWrapper.eq("APPROVE_ID",tApprove.getId());
//        TUserApproveConn tUserApproveConn = userApproveConnService.getOne(queryWrapper);
//        Integer approveTier = tUserApproveConn.getApproveTier();
        tApproveInfoDetail.setApproveRemark(remark);
//        如果approveTier1与approveTier 不相等
//  approveState  0：未审批 1：审批通过 2：审批驳回
//        要是审批通过，就要修改审批信息的状态为1，但是检查一下在此之前的是否存在审批驳回的，如果存在，就不修改审批信息的状态
        if (approveState == 1) {
            QueryWrapper<TApproveInfoDetail> queryWrapper8 = new QueryWrapper<>();
            queryWrapper8.eq("APPROVE_INFO_ID", tApproveInfoDetail.getApproveInfoId());
            queryWrapper8.eq("APPROVE_STATE", 2);
            TApproveInfoDetail tApproveInfoDetail1 = approveInfoDetailService.getOne(queryWrapper8);
//         如果tApproveInfoDetail1不为空，就不允许修改审批信息的状态
            if (tApproveInfoDetail1 != null) {
                return SzResult.Error("在您之前已有审批驳回的信息，不允许修改审批信息的状态");
            }
            tApproveInfo.setApproveState(1);
        }
        if (approveState == 2) {
            QueryWrapper<TApproveInfoDetail> queryWrapper9 = new QueryWrapper<>();
            queryWrapper9.eq("APPROVE_INFO_ID", tApproveInfoDetail.getApproveInfoId());
            queryWrapper9.eq("APPROVE_STATE", 1);
//            在我之后的审批信息，可以通过审批等级的大小来判断
            queryWrapper9.gt("APPROVE_TIER", tApproveInfoDetail.getApproveTier());
            TApproveInfoDetail tApproveInfoDetail1 = approveInfoDetailService.getOne(queryWrapper9);
//         如果tApproveInfoDetail1不为空，就不允许修改审批信息的状态
            if (tApproveInfoDetail1 != null) {
                return SzResult.Error("当前审批的上层审批已通过，不允许修改审批信息的状态,请联系上层审批人撤销审批信息");
            }
            tApproveInfo.setApproveState(2);
        }
        tApproveInfoDetail.setApproveState(approveState);
        approveInfoDetailService.updateById(tApproveInfoDetail);
        approveInfoService.updateById(tApproveInfo);
        return SzResult.Success();
    }

    //    撤销审批信息
    public SzResult revokeApprovalProcess(String token, String id, String remark, String plantId) throws Exception {
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        QueryWrapper<TApproveInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TApproveInfo tApproveInfo = approveInfoService.getOne(queryWrapper);
//    tApproveInfo.getApproveState()不为空或者0
        if (tApproveInfo.getApproveState() != null && tApproveInfo.getApproveState() != 0) {
            return SzResult.error("审批进行中或已完成，不能撤销");
        }
        tApproveInfo.setApproveState(10);
        tApproveInfo.setApproveRemark(remark);
        approveInfoService.updateById(tApproveInfo);
        return SzResult.Success();
    }

    //    删除审批信息
    public SzResult deleteApproval(String token, String id, String remark, String plantId) throws Exception {
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //String plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        QueryWrapper<TApproveInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TApproveInfo tApproveInfo = approveInfoService.getOne(queryWrapper);
//    tApproveInfo.getApproveState()不为空或者0
        if (tApproveInfo.getApproveState() != null && tApproveInfo.getApproveState() != 0) {
            return SzResult.error("审批进行中或已完成，不能删除");
        }
        tApproveInfo.setDelFlag(1);
        tApproveInfo.setApproveRemark(remark);
        approveInfoService.updateById(tApproveInfo);
        return SzResult.Success();
    }

    //    审批完成后，调用该方法，通过反射调用对应的方法
    public void approvalExecute(String functionName, Object[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Object bean = applicationContext.getBean("ApproveExecutionBu");
        Method method = bean.getClass().getDeclaredMethod(functionName, Object[].class);
        method.invoke(bean, (Object) args);
    }

    /**
     * 每个用户获取自己创建的审批
     *
     * @param token                                 审批状态
     * @param approveState(1通过，0审批流程未走完，2为驳回，10是撤销)
     * @return
     */
    public SzResult myApprove(Integer page, Integer pageSize, String token, Integer approveState, String approveId, String plantId) {
        String userId = StpUtil.getLoginIdByToken(token).toString();
        Page<TApproveInfo> page1 = new Page<>(page, pageSize);
        QueryWrapper<TApproveInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq(approveId != null, "APPROVE_ID", approveId);
        queryWrapper1.eq(approveState != null, "APPROVE_STATE", approveState);
        queryWrapper1.eq("DEL_FLAG", 0);
        queryWrapper1.eq(userId != null && userId.equals(""), "CREATE_BY", userId);
        queryWrapper1.eq("DATA_FROM", plantId);
        queryWrapper1.orderByDesc("CREATE_TIME");
        IPage<TApproveInfo> iPage = approveInfoService.page(page1, queryWrapper1);
        Map<String, Object> map = new HashMap<>();
        map.put("total", iPage.getTotal());
        map.put("list", iPage.getRecords());
        return SzResult.success(map);
    }

    /**
     * 审批人信息
     *
     * @param approveId
     * @param token
     * @return
     * @throws Exception
     */
    public SzResult approveUser(String approveId, String token, String plantId) throws Exception {
        QueryWrapper<TUserApproveConn> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("APPROVE_ID", approveId);
        queryWrapper.eq("DATA_FROM", plantId);
        List<TUserApproveConn> list = userApproveConnService.list(queryWrapper);
        List<Map<String, String>> mapList = new LinkedList<>();
        for (TUserApproveConn tUserApproveConn : list) {
            Map<String, String> map = new HashMap<>();
            String id = tUserApproveConn.getUserId();
            QueryWrapper<SysUser> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("ID", id);
            SysUser sysUser = userInfoDao.getUser(id);
            String trueName = sysUser.getTrueName();//审批人的姓名
            String phone = sysUser.getPhone();//审批人的手机号
            Integer approveTier = tUserApproveConn.getApproveTier();//审批的级别
            map.put("trueName", trueName);
            map.put("phone", phone);
            map.put("approveTier", approveTier.toString());
            mapList.add(map);
        }
        return SzResult.success(mapList);
    }

    public SzResult getApproveInfoExcel(String id) {
        TApproveInfo approveInfo = approveInfoService.getById(id);
        if (approveInfo == null) {
            return SzResult.error("不存在该审批");
        }
        TApprove approve = approveService.getById(approveInfo.getApproveId());
        if (approve == null) {
            return SzResult.error("不存在该审批类型");
        }
        TApprovalTemplate approvalTemplate = approvalTemplateService.getById(approve.getTemplateId());
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> date = JSON.parseObject(approveInfo.getExecutionData()).toJavaObject(Map.class);
        QueryWrapper<TUserApproveConn> userApproveConnQueryWrapper = new QueryWrapper<>();
        userApproveConnQueryWrapper.eq("APPROVE_ID", approveInfo.getApproveId());
        userApproveConnQueryWrapper.orderByAsc("APPROVE_TIER");
        Set<String> set = new HashSet<>();
        List<UserApproveVo> list = userApproveConnService.list(userApproveConnQueryWrapper).stream()
                .map(item -> {
                    UserApproveVo userApproveVo = new UserApproveVo();
                    userApproveVo.setBranch(item.getBranch());
                    QueryWrapper<TApproveInfoDetail> approveInfoDetailQueryWrapper = new QueryWrapper<>();
                    approveInfoDetailQueryWrapper.eq("APPROVE_INFO_ID", id);
                    approveInfoDetailQueryWrapper.eq("APPROVE_USER_ID", item.getUserId());
                    approveInfoDetailQueryWrapper.eq("DEL_FLAG", 0);
                    if (approveInfo.getApproveState() != 0){
                        TApproveInfoDetail approveInfoDetail = approveInfoDetailService.getOne(approveInfoDetailQueryWrapper);

                        if (approveInfoDetail == null) {
                            userApproveVo.setState("");
                            userApproveVo.setUserName("");
                            userApproveVo.setDate("");
                        } else {
                            userApproveVo.setState(approveInfoDetail.getApproveRemark());
                            try {
                                SysUser user = userInfoDao.getUser(item.getUserId());
                                if (user != null) {
                                    userApproveVo.setUserName(user.getTrueName());
                                } else {
                                    userApproveVo.setUserName("");
                                }
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                            userApproveVo.setDate(approveInfoDetail.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
                        }
                    }
                    return userApproveVo;
                }).filter(i->{
                    if (approveInfo.getApproveState() != 0) {
                        return StringUtils.isNotEmpty(i.getUserName());
                    }else {
                       return set.add(i.getBranch());
                    }
                }
//
                ).collect(Collectors.toList());

        map.put("approveTemplate", approvalTemplate.getApproveTemplate());
        map.put("branchList", list);
        map.put("date", date);
        return SzResult.success(map);
    }

    static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        //putIfAbsent方法添加键值对，如果map集合中没有该key对应的值，则直接添加，并返回null，如果已经存在对应的值，则依旧为原来的值。
        //如果返回null表示添加数据成功(不重复)，不重复(null==null :TRUE)
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    public SzResult getApproveTemplate() {
        return SzResult.success(approvalTemplateService.list());
    }

    public SzResult updateApproveInfoDate(String id, Map<String, Object> map) {
        QueryWrapper<TApproveInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TApproveInfo tApproveInfo1 = approveInfoService.getOne(queryWrapper);
        if (tApproveInfo1 == null) {
            return SzResult.error("不存在该审批单");
        }
//        if (tApproveInfo1.getApproveState() != 0) {
//            return SzResult.error("审批已经结束，不能修改");
//        }
        TApproveInfo tApproveInfo = new TApproveInfo();
        tApproveInfo.setId(id);
        tApproveInfo.setApproveId(map.get("approveId").toString());
        QueryWrapper<TApprove> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("ID", map.get("approveId").toString());
        TApprove tApprove = approveService.getOne(queryWrapper1);
        if (tApprove == null) {
            return SzResult.error("不存在该审批类型");
        }
        tApproveInfo.setApproveTier(tApprove.getApproveTier());
        tApproveInfo.setApproveInfo(map.get("title").toString());
        tApproveInfo.setExecutionData(new JSONObject(map).toString());
        return SzResult.success(approveInfoService.updateById(tApproveInfo));
    }

    //    删除审批数据
    public SzResult deleteApproveInfo(String id) {
        QueryWrapper<TApproveInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID", id);
        TApproveInfo tApproveInfo1 = approveInfoService.getOne(queryWrapper);
        if (tApproveInfo1 == null) {
            return SzResult.error("不存在该审批单");
        }
        if (tApproveInfo1.getApproveState() != 0) {
            return SzResult.error("审批已经结束，不能删除");
        }
        tApproveInfo1.setDelFlag(1);
        return SzResult.success(approveInfoService.updateById(tApproveInfo1));
    }
}
